package com.example.samchan.music_player_0;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.AudioManager;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.example.samchan.music_player_0.data.Music;
import com.example.samchan.music_player_0.data.MusicList;
import com.example.samchan.music_player_0.model.PropertyBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    // 权限请求代码
    private static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 725;
    private static final int MY_PERMISSIONS_REQUEST_READ_PHONE_STATE = 464;
    // 显示组件
    private ImageButton imgBtn_Previous;
    private ImageButton imgBtn_PlayOrPause;
    private ImageButton imgBtn_Stop;
    private ImageButton imgBtn_Next;
    private ListView music_List;
    private RelativeLayout root_Layout;
    private ImageButton imgBtn_PlayMode;
    private ImageButton imgBtn_VolumeSwitch;

    // 歌曲列表对象
    private ArrayList<Music> musicArrayList;

    // 当前歌曲的序号，从0开始
    private int MusicIndex = 0;

    // 播放状态
    private int status;
    private int duration;
    private int nowIndex; // 歌曲当前时间戳

    // 广播接收器
    private StatusChangeReceiver receiver;
    private TextView nowPlaying;
    private TextView nowArtistAlbum;

    // 进度条相关
    private TextView nowDuration;
    private TextView nowTime;
    private SeekBar seekBar;
    private boolean isSeekBarOnTouch = false;

    // 播放模式常量
    private int playmode;

    // 退出判断标志
    private static boolean readyExit = false;

    // 音量控制相关
    private SeekBar seekBar_volume;
    private int savedVol = 0;

    // 睡眠模式相关
    private ImageView imgView_sleep;
    private static boolean isSleepModeOn;
    private int sleepMinutes;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            super.onStop();
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);

        } else if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            super.onStop();
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_PHONE_STATE},
                    MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);

        } else {
            setContentView(R.layout.activity_main);
            findViews();
            registerListeners();
            initMusicList();
            initListView();
            checkMusicFile();
            // 绑定广播接收器
            bindStatusChangeReceiver();
            startService(new Intent(this, PlayerService.class));
            status = PlayerService.COMMAND_STOP;
            nowIndex = 0;
            duration = 0;
            // 默认睡眠模式为关闭
            isSleepModeOn = false;
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(this, "read storage permission request was denied....", Toast.LENGTH_SHORT).show();
                }
                return;
            } case MY_PERMISSIONS_REQUEST_READ_PHONE_STATE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(this, "read phone state permission request was denied....", Toast.LENGTH_SHORT).show();
                }
                return;
            } default: {
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            }
            // other 'case' lines to check for other
            // permissions this app might request.
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        sendBroadcastOnCommand(PlayerService.COMMAND_CHECK_IS_PLAYING);
        PropertyBean property = new PropertyBean(MainActivity.this);
        String theme = property.getTheme();
        setTheme(theme);
        initAudioControl();
        // 睡眠模式图标
        if (isSleepModeOn) {
            imgView_sleep.setVisibility(View.VISIBLE);
        } else {
            imgView_sleep.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    protected void onDestroy() {
        if (status == PlayerService.STATUS_STOPPED) {
            stopService(new Intent(this, PlayerService.class));
        }
        super.onDestroy();
        System.exit(0);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK: {
                exitByDoubleClick();
                break;
            }
            case KeyEvent.KEYCODE_VOLUME_DOWN: {
                int progress = seekBar_volume.getProgress();
                if (progress != 0) {
                    seekBar_volume.setProgress(progress - 1);
                }
                return true;
            }
            case KeyEvent.KEYCODE_VOLUME_UP: {
                int progress = seekBar_volume.getProgress();
                if (progress != seekBar_volume.getMax()) {
                    seekBar_volume.setProgress(progress + 1);
                }
                return true;
            }
            default: {
                break;
            }
        }
        return false;
    }

    private void exitByDoubleClick() {
        Timer timer = null;
        if (readyExit == false) {
            readyExit = true;
            Toast.makeText(this, "再按一次退出！", Toast.LENGTH_SHORT).show();
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    readyExit = false;
                }
            }, 2000);
        } else {
            System.exit(0);
        }
    }

    // 绑定广播接收器
    private void bindStatusChangeReceiver() {
        receiver = new StatusChangeReceiver();
        IntentFilter filter = new IntentFilter(PlayerService.BROADCAST_PLAYERSERVICE_UPDATE_STATUS);
        registerReceiver(receiver, filter);
    }

    // 获取显示组件
    private void findViews() {
        imgBtn_Previous = findViewById(R.id.imgBtnPre);
        imgBtn_PlayOrPause = findViewById(R.id.imgBtnPlay);
        imgBtn_Stop = findViewById(R.id.imgBtnStop);
        imgBtn_Next = findViewById(R.id.imgBtnNext);
        music_List = findViewById(R.id.musicListLayout);
        root_Layout = findViewById(R.id.mainLayout);
        nowPlaying = findViewById(R.id.songsName);
        nowArtistAlbum = findViewById(R.id.songsArtistAlbum);
        nowDuration = findViewById(R.id.songDuration);
        nowTime = findViewById(R.id.timeIndex);
        seekBar = findViewById(R.id.mDurationSeekBar);
        imgBtn_PlayMode = findViewById(R.id.imgBtnPlayMode);
        imgBtn_VolumeSwitch = findViewById(R.id.imgBtnVolume);
        seekBar_volume = findViewById(R.id.seekBarVolume);
        imgView_sleep = findViewById(R.id.main_iv_sleep);
    }

    // 为显示组件注册监听器
    private void registerListeners() {
        imgBtn_Previous.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendBroadcastOnCommand(PlayerService.COMMAND_PREVIOUS);
            }
        });
        imgBtn_PlayOrPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (status) {
                    case PlayerService.STATUS_PLAYING: {
                        sendBroadcastOnCommand(PlayerService.COMMAND_PAUSE);
                        break;
                    }
                    case PlayerService.STATUS_PAUSED: {
                        sendBroadcastOnCommand(PlayerService.COMMAND_RESUME);
                        break;
                    }
                    case PlayerService.STATUS_STOPPED: {
                        sendBroadcastOnCommand(PlayerService.COMMAND_PLAY);
                        break;
                    }
                    default: {
                        break;
                    }
                }
            }
        });
        imgBtn_Stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendBroadcastOnCommand(PlayerService.COMMAND_STOP);
            }
        });
        imgBtn_Next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendBroadcastOnCommand(PlayerService.COMMAND_NEXT);
            }
        });
        music_List.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MusicIndex = position;
                sendBroadcastOnCommand(PlayerService.COMMAND_PLAY);
            }
        });
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (status != PlayerService.STATUS_STOPPED) {
                    nowIndex = progress;
                    nowTime.setText(formatTime(nowIndex));
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 进度条暂停移动
                isSeekBarOnTouch = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                isSeekBarOnTouch = false;
                if (status != PlayerService.STATUS_STOPPED) {
                    nowIndex = seekBar.getProgress();
                    nowTime.setText(formatTime(nowIndex));
                    sendBroadcastOnCommand(PlayerService.COMMAND_SEEK_TO);
                }
                if (status == PlayerService.STATUS_PLAYING) {
                    sendBroadcastOnCommand(PlayerService.COMMAND_SEEK_TO);
                }
                if (status == PlayerService.STATUS_PAUSED) {
                    sendBroadcastOnCommand(PlayerService.COMMAND_SEEK_TO);
                    sendBroadcastOnCommand(PlayerService.COMMAND_RESUME);
                }
            }
        });
        imgBtn_PlayMode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] mode = new String[] {"顺序播放", "单曲循环", "列表循环", "随机播放"};
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("播放模式");
                builder.setSingleChoiceItems(mode, playmode,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                playmode = which;
                            }
                        });
                builder.setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (playmode) {
                                    case 0: {
                                        playmode = PlayerService.MODE_LIST_SEQUENCE;
                                        Toast.makeText(getApplicationContext(), R.string.list_seq, Toast.LENGTH_SHORT).show();
                                        break;
                                    }
                                    case 1: {
                                        playmode = PlayerService.MODE_SINGLE_CYCLE;
                                        Toast.makeText(getApplicationContext(), R.string.single_cyc, Toast.LENGTH_SHORT).show();
                                        break;
                                    }
                                    case 2: {
                                        playmode = PlayerService.MODE_LIST_CYCLE;
                                        Toast.makeText(getApplicationContext(), R.string.list_cyc, Toast.LENGTH_SHORT).show();
                                        break;
                                    }
                                    case 3: {
                                        playmode = PlayerService.MODE_RANDOM;
                                        Toast.makeText(getApplicationContext(), R.string.random_play, Toast.LENGTH_SHORT).show();
                                    }
                                    default: break;
                                }
                                sendBroadcastOnCommand(PlayerService.COMMAND_MODE_CHANGE);
                            }
                        });
                builder.create().show();
            }
        });
        imgBtn_VolumeSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (seekBar_volume.getProgress() != 0) {
                    savedVol = seekBar_volume.getProgress();
                    seekBar_volume.setProgress(0);
                } else {
                    if (savedVol != 0) {
                        seekBar_volume.setProgress(savedVol);
                    } else {
                        seekBar_volume.setProgress(5);
                    }
                }
            }
        });
        // 将列表跳到当前播放歌曲
        nowPlaying.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                music_List.setSelection(MusicIndex);
            }
        });
    }

    private void initMusicList() {
        musicArrayList = MusicList.getMusicArrayList();

        if (musicArrayList.isEmpty()) {
            Cursor mMusicCursor = this.getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    new String[] {
                            MediaStore.Audio.Media.TITLE,
                            MediaStore.Audio.Media.DURATION,
                            MediaStore.Audio.Media.ALBUM,
                            MediaStore.Audio.Media.ALBUM_ID,
                            MediaStore.Audio.Media.ARTIST,
                            MediaStore.Audio.Media._ID,
                            MediaStore.Audio.Media.DATA,
                            MediaStore.Audio.Media.DISPLAY_NAME
                    }, null, null,
                    MediaStore.Audio.AudioColumns.TITLE
            );

            if (mMusicCursor != null) {
                int indexTitle = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);
                int indexArtist = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);
                int indexDuration = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION);
                int indexPath = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);
                int indexAlbum = mMusicCursor.getColumnIndex(MediaStore.Audio.AlbumColumns.ALBUM);
                int indexABID = mMusicCursor.getColumnIndex(MediaStore.Audio.AlbumColumns.ALBUM_ID);

                // 遍历数据库，并将Music类对象加载到ArrayList中
                for (mMusicCursor.moveToFirst(); !mMusicCursor.isAfterLast(); mMusicCursor.moveToNext()) {
                    String strTitle = mMusicCursor.getString(indexTitle);
                    String strArtist = mMusicCursor.getString(indexArtist);
                    String strDuration = mMusicCursor.getString(indexDuration);
                    String strPath = mMusicCursor.getString(indexPath);
                    String strAlbum = mMusicCursor.getString(indexAlbum);
                    long lngAlbumID = mMusicCursor.getLong(indexABID);

                    if (strArtist.equals("<unknown>"))
                        strArtist = "未知艺术家";
                    Music music = new Music(strTitle, strArtist, strPath, strDuration, strAlbum, lngAlbumID);
                    musicArrayList.add(music);
                }
            }
        }
    }

    private void initListView() {
        List<Map<String, String>> list_map = new ArrayList<>();
        HashMap<String, String> map;
        SimpleAdapter simpleAdapter;
        for (Music music : musicArrayList) {
            map = new HashMap<>();
            map.put("musicName", music.getMusicName());
            map.put("musicArtist", music.getMusicArtist());
            list_map.add(map);
        }

        String[] from = new String[] {"musicName", "musicArtist"};
        int[] to = {R.id.mscLV_Title, R.id.mscLV_Artist};

        simpleAdapter = new SimpleAdapter(this, list_map, R.layout.music_list, from, to);
        music_List.setAdapter(simpleAdapter);
    }

    private void checkMusicFile() {
        if (musicArrayList.isEmpty()) {
            imgBtn_Previous.setEnabled(false);
            imgBtn_PlayOrPause.setEnabled(false);
            imgBtn_Stop.setEnabled(false);
            imgBtn_Next.setEnabled(false);
            Toast.makeText(getApplicationContext(), "没有歌曲在列表", Toast.LENGTH_SHORT).show();
        } else {
            imgBtn_Previous.setEnabled(true);
            imgBtn_PlayOrPause.setEnabled(true);
            imgBtn_Stop.setEnabled(true);
            imgBtn_Next.setEnabled(true);
        }
    }

    // 播放器Service控制命令发送函数
    private void sendBroadcastOnCommand(int command) {
        Intent intent = new Intent(PlayerService.BROADCAST_PLAYERSERVICE_CONTROL);
        intent.putExtra("command", command);
        // 封装数据
        switch (command) {
            case PlayerService.COMMAND_PLAY: {
                intent.putExtra("musicIndex", MusicIndex);
                break;
            } case PlayerService.COMMAND_PREVIOUS: {
                break;
            } case PlayerService.COMMAND_NEXT: {
                break;
            } case PlayerService.COMMAND_PAUSE: {
                break;
            } case PlayerService.COMMAND_STOP: {
                break;
            } case PlayerService.COMMAND_RESUME: {
                break;
            } case PlayerService.COMMAND_SEEK_TO: {
                intent.putExtra("timeIndex", nowIndex);
                break;
            } case PlayerService.COMMAND_CHECK_IS_PLAYING: {
                break;
            }case PlayerService.COMMAND_MODE_CHANGE: {
                intent.putExtra("playmode", playmode);
                switch (playmode) {
                    case PlayerService.MODE_LIST_SEQUENCE: {
                        imgBtn_PlayMode.setBackgroundResource(R.mipmap.mode_list_seq);
                        break;
                    }case PlayerService.MODE_SINGLE_CYCLE: {
                        imgBtn_PlayMode.setBackgroundResource(R.mipmap.mode_single_cyc);
                        break;
                    }case PlayerService.MODE_LIST_CYCLE: {
                        imgBtn_PlayMode.setBackgroundResource(R.mipmap.mode_list_cyc);
                        break;
                    }case PlayerService.MODE_RANDOM: {
                        imgBtn_PlayMode.setBackgroundResource(R.mipmap.mode_random);
                        break;
                    } default: { break; }
                }
                break;
            }case PlayerService.COMMAND_SET_SLEEP_TIME: {
                intent.putExtra("newSleepTime", sleepMinutes);
                break;
            }
            default: {
                break;
            }
        }
        sendBroadcast(intent);
    }

    // 主题设置函数
    private void setTheme(String theme) {
        if ("彩色".equals(theme)) {
            root_Layout.setBackgroundResource(R.mipmap.bg_color);
        } else if ("花朵".equals(theme)) {
            root_Layout.setBackgroundResource(R.mipmap.bg_digit_flower);
        } else if ("群山".equals(theme)) {
            root_Layout.setBackgroundResource(R.mipmap.bg_mountain);
        } else if ("小狗".equals(theme)) {
            root_Layout.setBackgroundResource(R.mipmap.bg_running_dog);
        } else if ("冰雪".equals(theme)) {
            root_Layout.setBackgroundResource(R.mipmap.bg_snow);
        } else if ("女孩".equals(theme)) {
            root_Layout.setBackgroundResource(R.mipmap.bg_music_girl);
        } else if ("朦胧".equals(theme)) {
            root_Layout.setBackgroundResource(R.mipmap.bg_blur);
        }
    }

    // 创建菜单
    public boolean onCreateOptionsMenu(Menu menu) {
        this.getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    // 处理菜单点击事件
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_theme: {
                new AlertDialog.Builder(this)
                        .setTitle("请选择主题")
                        .setItems(R.array.theme,
                                new android.content.DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        String theme = PropertyBean.THEMES[which];
                                        MainActivity.this.setTheme(theme);
                                        PropertyBean property = new PropertyBean(MainActivity
                                                .this);
                                        property.setAndSaveTheme(theme);
                                    }
                                })
                        .show();
                break;
            }
            case R.id.menu_play_mode: {
                String[] mode = new String[] {"顺序播放", "单曲循环", "列表循环", "随机播放"};
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("播放模式");
                builder.setSingleChoiceItems(mode, playmode,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                playmode = which;
                            }
                        });
                builder.setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (playmode) {
                                    case 0: {
                                        playmode = PlayerService.MODE_LIST_SEQUENCE;
                                        Toast.makeText(getApplicationContext(), R.string.list_seq, Toast.LENGTH_SHORT).show();
                                        break;
                                    }
                                    case 1: {
                                        playmode = PlayerService.MODE_SINGLE_CYCLE;
                                        Toast.makeText(getApplicationContext(), R.string.single_cyc, Toast.LENGTH_SHORT).show();
                                        break;
                                    }
                                    case 2: {
                                        playmode = PlayerService.MODE_LIST_CYCLE;
                                        Toast.makeText(getApplicationContext(), R.string.list_cyc, Toast.LENGTH_SHORT).show();
                                        break;
                                    }
                                    case 3: {
                                        playmode = PlayerService.MODE_RANDOM;
                                        Toast.makeText(getApplicationContext(), R.string.random_play, Toast.LENGTH_SHORT).show();
                                    }
                                    default: break;
                                }
                                sendBroadcastOnCommand(PlayerService.COMMAND_MODE_CHANGE);
                            }
                        });
                builder.create().show();

                break;
            }
            case R.id.menu_sleep_setting: {
                showSleepSettingDialog();
                break;
            }
            case R.id.menu_about: {
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle(R.string.app_name)
                        .setMessage(R.string.about2).show();
                break;
            }
            case R.id.menu_quit: {
                new AlertDialog.Builder(this)
                        .setTitle("提示")
                        .setMessage("退出")
                        .setPositiveButton("确定",
                                new android.content.DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface arg0, int arg1) {
                                        System.exit(0);
                                    }
                                })
                        .setNegativeButton("取消",
                                new android.content.DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface arg0, int arg1) {
                                    }
                                })
                        .show();
                break;
            }
        }
        return super.onOptionsItemSelected(item);
    }

    // 睡眠模式设置菜单
    private void showSleepSettingDialog()
    {
        // 先用getLayoutInflater().inflate方法获取布局，用来初始化一个View类对象
        final View userView = this.getLayoutInflater().inflate(R.layout.menu_sleep_mode_dialog, null);

        // 通过View类的findViewById方法获取到组件对象
        final TextView textView_minutes = userView.findViewById(R.id.menu_sleep_mode_dialog_tv);
        final Switch switch1 = userView.findViewById(R.id.menu_sleep_mode_dialog_switch);
        final SeekBar seekBar = userView.findViewById(R.id.menu_sleep_mode_dialog_seekBar);

        textView_minutes.setText("睡眠于:" + sleepMinutes + "分钟");
        // 根据当前的睡眠状态来确定Switch的状态
        if (isSleepModeOn) {
            switch1.setChecked(true);
        }
        seekBar.setMax(60); // 最多60分钟
        seekBar.setProgress(sleepMinutes);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                sleepMinutes = progress;
                textView_minutes.setText("睡眠于:" + sleepMinutes + "分钟");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isSleepModeOn = isChecked;
            }
        });
        // 定义对话框以及初始化
        final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle("选择睡眠时间(0~60分钟)");
        dialog.setView(userView);
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.setNeutralButton("重置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                sleepMinutes = 20;
                sendBroadcastOnCommand(PlayerService.COMMAND_SET_SLEEP_TIME);
                imgView_sleep.setVisibility(View.VISIBLE);
            }
        });
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (isSleepModeOn) {
                    sleepMinutes = seekBar.getProgress();
                    imgView_sleep.setVisibility(View.VISIBLE);
                } else {
                    sleepMinutes = 0;
                    imgView_sleep.setVisibility(View.INVISIBLE);
                    dialog.dismiss();
                }
                sendBroadcastOnCommand(PlayerService.COMMAND_SET_SLEEP_TIME);
            }
        });
        dialog.show();
    }

    // 时间格式化
    private String formatTime(int msec) {
        int minute = msec / 1000 / 60;
        int second = msec / 1000 % 60;
        String minuteString;
        String secondString;
        if (minute < 10) {
            minuteString = "0" + minute;
        } else {
            minuteString = "" + minute;
        }
        if (second < 10) {
            secondString = "0" + second;
        } else {
            secondString = "" + second;
        }
        return minuteString + ":" + secondString;
    }

    // 音量控制
    private void initAudioControl() {
        // 获取音量管理器
        final AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        // 设置当前音量大小只针对媒体音量
        this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
        // 设置音量seekBar最大值
        final int max_VolumeProgress = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        seekBar_volume.setMax(max_VolumeProgress);
        // 获取当前音量
        int volumeProgress = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        seekBar_volume.setProgress(volumeProgress);

        updateImgBtnVolBG(volumeProgress, max_VolumeProgress);

        seekBar_volume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                updateImgBtnVolBG(progress, seekBar.getMax());
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, AudioManager.FLAG_PLAY_SOUND);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    // 音量按钮图片更新
    void updateImgBtnVolBG(int vol, int max) {
        if (vol == 0) {
            imgBtn_VolumeSwitch.setBackgroundResource(R.mipmap.volume_off);
        } else {
            double temp = (double) vol / (double) max;
            if (temp > 0) {
                imgBtn_VolumeSwitch.setBackgroundResource(R.mipmap.volume_low);
            }
            if (temp > 0.5) {
                imgBtn_VolumeSwitch.setBackgroundResource(R.mipmap.volume_high);
            }
        }
    }


    // 播放器状态更新广播的接收
    class StatusChangeReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            String musicName = intent.getStringExtra("musicName");
            String musicArtist = intent.getStringExtra("musicArtist");
            String musicAlbum = intent.getStringExtra("musicAlbum");
            // 获取播放器状态
            status = intent.getIntExtra("status", PlayerService.STATUS_UNKNOWN);
            isSleepModeOn = intent.getBooleanExtra("isSleep", false);
            if (isSleepModeOn) {
                imgView_sleep.setVisibility(View.VISIBLE);
            } else {
                imgView_sleep.setVisibility(View.INVISIBLE);
            }
            sleepMinutes = intent.getIntExtra("sleepTime", 0);
            int command = intent.getIntExtra("command", PlayerService.COMMAND_UNKNOWN);
            if (command == PlayerService.COMMAND_EXIT) {
                System.exit(0);
            }
            switch (status) {
                case PlayerService.STATUS_PLAYING: {
                    if (command == PlayerService.COMMAND_UPDATE_TIME) {
                        nowIndex = intent.getIntExtra("timeIndex", 0);
                        updateSeekbar();
                    } else {
                        imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
                        nowPlaying.setText(musicName);
                        nowArtistAlbum.setText(musicArtist + " - " + musicAlbum);
                        duration = intent.getIntExtra("musicDuration", 0);
                        nowDuration.setText(formatTime(duration));
                        seekBar.setMax(duration);
                        nowIndex = intent.getIntExtra("timeIndex", 0);
                        updateSeekbar();
                    }
                    break;
                }
                case PlayerService.STATUS_PAUSED: {
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_play);
                    break;
                }
                case PlayerService.STATUS_STOPPED: {
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_play);
                    nowPlaying.setText(R.string.not_playing);
                    nowArtistAlbum.setText("");
                    duration = 0;
                    nowIndex = 0;
                    restSeekbar();
                    nowTime.setText(R.string.not_playing_time);
                    nowDuration.setText(R.string.not_playing_time);
                    break;
                }
                case PlayerService.STATUS_COMPLETED: {
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_play);
                    MusicIndex = intent.getIntExtra("musicIndex", 0);
                    nowPlaying.setText(R.string.not_playing);
                    restSeekbar();
                    nowArtistAlbum.setText("");
                    nowTime.setText(R.string.not_playing_time);
                    nowDuration.setText(R.string.not_playing_time);
                    break;
                }
                default: {
                    break;
                }
            }
        }
    }

    private void updateSeekbar() {
        if (!isSeekBarOnTouch) {
            if (seekBar.getProgress() < duration) {
                // 更新进度条
                seekBar.setProgress(nowIndex);
                // 更新UI文本
                nowTime.setText(formatTime(nowIndex));
            }
        }
    }

    private void restSeekbar() {
        // 重置进度条画面
        seekBar.setProgress(0);
    }
}
